﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.Iservice;
using ZSZ.Service.Entity;

namespace ZSZ.Service
{
    public class CityService : ICityService
    {
        private CityDTO ToDTO(CityEntity e) {
            CityDTO d = new CityDTO();
            d.CreateTime = e.CreateDatatime;
            d.Id = e.Id;
            d.Name = e.Name;
            return d;
        }
        public CityDTO[] GetAll()
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<CityEntity> cs = new CommonService<CityEntity>(ct);
                return cs.GetAll().AsNoTracking().ToList().Select(c=>ToDTO(c)).ToArray();
            }
        }

        public CityDTO GetById(long id)
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<CityEntity> cs = new CommonService<CityEntity>(ct);
                if (!cs.GetAll().Any(c=>c.Id==id))
                {
                    throw new ArgumentException("没有这个city");
                }
                return ToDTO(cs.GetById(id));
            }
        }

        public long AddNew(string name)
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<CityEntity> cs = new CommonService<CityEntity>(ct);
                bool exits = cs.GetAll().AsNoTracking().Any(a=>a.Name==name);
                if (exits)
                {
                    throw new ArgumentException("这个名字已经存在了");
                }
                CityEntity city = new CityEntity();
                city.Name = name;
                ct.Cities.Add(city);
                ct.SaveChanges();
                return city.Id;
            }
        }
    }
}
